<?php

namespace App\Models;

use App\Wechat\Init;
use Dcat\Admin\Traits\HasDateTimeFormatter;

use Illuminate\Database\Eloquent\Model;

class Hospital extends Model
{
	use HasDateTimeFormatter;
    protected $table = 'eb_hospital';
    public static function typeLabels($k,$v){
        $vaccines=Hospital::all()->toArray();
        $key=array_column($vaccines,$k);
        $value=array_column($vaccines,$v);
        return array_combine($key,$value);
    }

    public static function booted()
    {
        parent::booted();
        static::created(function ($model){
            self::createQrcode($model);
        });
        static::updated(function ($model){
            self::createQrcode($model);
        });
    }
    public static function createQrcode($model)
    {
        if(empty($model->qrcode)){
            $qrcodeid=Qrcodeid::query()->where(['mappingid'=>$model->id,'type'=>0])->first();
            if(!$qrcodeid){
                $qrcodeid=new Qrcodeid();
                $qrcodeid->mappingid=$model->id;
                $qrcodeid->save();
            }
            $app = new Init();
            $api=$app->getApp()->getClient();
            $options = [
                    'json'=> [
                        'action_name' => "QR_LIMIT_SCENE",
                        'action_info' =>
                            [
                                'scene' => ['scene_id' => $qrcodeid->qrcodeid]
                            ]
                    ]
                ];
            $response = $api->post('/cgi-bin/qrcode/create', $options);
            $wxResponse = json_decode($response->getContent(),true); // 这里会抛出异常

            if(isset($wxResponse['url']) ){
                $model->qrcode = $wxResponse['url'];
                $model->save();
            }
        }
    }


    public function familys(){

        return $this->belongsToMany(Family::class,'eb_hospital_user_family','hospital_id','family_id');
    }
}
